package org.arch_learn.io.nio.channel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

public class NioChannelClientDemo {
    public static void main(String[] args) throws IOException {
        //1.打开客户端通道
        SocketChannel socketChannel = SocketChannel.open();
        //2.设置连接ip和端口号
        socketChannel.connect(new InetSocketAddress("127.0.0.1", 9999));
        //3.写出数据
        ByteBuffer byteBuffer = ByteBuffer.wrap("hello there!".getBytes(StandardCharsets.UTF_8));
        socketChannel.write(byteBuffer);
        //4.读取服务端返回的数据
        ByteBuffer responseByteBuffer = ByteBuffer.allocate(1024);
        int read = socketChannel.read(responseByteBuffer);
        String responseMessage = new String(responseByteBuffer.array(), 0, read, StandardCharsets.UTF_8);
        System.out.println("获取服务端响应消息为：" + responseMessage);
        //5.释放资源
        socketChannel.close();
    }
}
